﻿using AspNet.Identity.Dapper.Db;
using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AspNet.Identity.Dapper
{
    public class RoleTable
    {
        private readonly DbManager _db;

        public RoleTable(DbManager dbManager)
        {
            this._db = dbManager;
        }

        public bool Delete(Guid roleId)
        {
            return _db.Connection.Execute(@"delete from role where id=@id", new { id = roleId.ToString() })>0;
        }

        public bool  Insert(IdentityRole role)
        {
            return _db.Connection.Execute(@"insert into role (id,name) values (@id,@name)", new { id = role.Id.ToString(), name = role.Name })>0;
        }

        public string GetRoleName(Guid id)
        {
            return _db.Connection.ExecuteScalar<string>(@"select name from role where id=@id", new { id=id.ToString() });
        }

        public Guid GetRoleId(string name)
        {
            var id= _db.Connection.ExecuteScalar<string>(@"select id from role where name=@name limit 1", new { name });
            return Guid.Parse(id);
        }

        public IdentityRole GetRoleById(Guid id)
        {
            return _db.Connection.QueryFirst<IdentityRole>(@"select Id as IdString, Name from role where id=@id", new { id=id.ToString() });
        }

        public IdentityRole GetRoleByName(string name)
        {
            return _db.Connection.QueryFirst<IdentityRole>(@"select Id as IdString,Name from role where name=@name", new { name });
        }

        public bool Update(IdentityRole role)
        {
            return _db.Connection.Execute(@"update role set name=@name where id=@id",new { id=role.Id.ToString(),name=role.Name })>0;
        }

    }
}
